package com.gcd.tempe.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

import com.gcd.tempe.LihatBarangActivity;
import com.gcd.tempe.util.GlobalVariabel;
import com.gcd.tempe.util.JSON_Response;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Cart {
	private static final String urlPostfix = "pesanan.add";
	private static final String userName = "&username=";
	private static final String password = "&password=";
	private static final String useNoPoint = "&use_point=0";
	private static final String usePoint = "&use_point=1";
	private static final String useShipping = "&kirim=1";
	
	GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.setExclusionStrategies(new ExclusionStrategy() {

        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }

		public boolean shouldSkipField(FieldAttributes f) {
			return f.getName().equals("deskripsi") || f.getName().equals("harga_satuan") || f.getName().equals("kategori_id") || f.getName().equals("nama");
		}
    }).create();
    
	public ArrayList<Barang> itemsCart;
	
	public Cart(){
		itemsCart = new ArrayList<Barang>();  
	}
	
	public void addItemToItemsCart(Barang item) {
		itemsCart.add(item);
	}
	
	public String orderItemsInItemsCart(Boolean usePoint, Boolean useShipping, String address, String shippingID){
		String userName_URL = Cart.userName + GlobalVariabel.userLoginInfo.userName;
		String password_URL = Cart.password + GlobalVariabel.userLoginInfo.password;
		String jsonPesanan = gson.toJson(itemsCart);
		StringBuilder builder = new StringBuilder();

		//Kirim data jsonPesanan liwat method POST :
		// Create a new HttpClient and Post Header
	    HttpClient httpclient = new DefaultHttpClient();
	    String responseString = "Gagal ini";
	    HttpPost httppost;
		
		if (usePoint) {			
			if (useShipping) {
				Log.d("Order", "pake poin & pake shipping");
				httppost = new HttpPost(JSON_Response.baseUrl + urlPostfix + userName_URL + password_URL + Cart.usePoint + Cart.useShipping) ;
            } else {
            	Log.d("Order", "gak pake poin & pake shipping");
            	httppost = new HttpPost(JSON_Response.baseUrl + urlPostfix + userName_URL + password_URL + Cart.usePoint) ;
            }
		} else {
			if (useShipping) {
				Log.d("Order", "gak pake poin & pake shipping");
				httppost = new HttpPost(JSON_Response.baseUrl + urlPostfix + userName_URL + password_URL + Cart.useNoPoint + Cart.useShipping);
            } else {
            	Log.d("Order", "gak pake poin & gak pake shipping");
            	httppost = new HttpPost(JSON_Response.baseUrl + urlPostfix + userName_URL + password_URL);
            }
		}

	    try {
	    	Log.d("Order", jsonPesanan);
	    	// Add  data
	    	List<NameValuePair> postParameters = new ArrayList<NameValuePair>(3);  
            postParameters.add(new BasicNameValuePair("data", jsonPesanan)); 
            if (useShipping) {
			    postParameters.add(new BasicNameValuePair("alamat_kirim", address));
			    postParameters.add(new BasicNameValuePair("shipping_service_id", shippingID));
            }
            httppost.setEntity(new UrlEncodedFormEntity(postParameters));  
            
	        // Execute HTTP Post Request
	    	HttpResponse response = httpclient.execute(httppost);  
	        StatusLine statusLine = response.getStatusLine();
			
	        int statusCode = statusLine.getStatusCode();
	        Log.d("Order", "StatusCOde : "+statusCode);
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
				responseString = builder.toString();
			} else {
				Log.e(LihatBarangActivity.class.toString(), "Failed to download file");
			}
	    } catch (ClientProtocolException e) {
	        // TODO Auto-generated catch block
	    } catch (IOException e) {
	        // TODO Auto-generated catch block
	    }
		
	    return responseString;
	}
	
	public void clearCart(){
		itemsCart.clear();
	}
	
}
